package com.ytf.dogbox.util;

import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author tiwolf_li
 * @Date on 2020/6/23
 * @Description  android 11的路径为另外的  /storage/emulated/0/Android/data/intefly.tiwolf.mqttcameraplus/files/photoeditor
 */
public class FileSortUtil {

    public static String appPath= Environment.getExternalStorageDirectory()+"/solar/";
    public static String appVer=Environment.getExternalStorageDirectory()+"/version";
    public static String boardVer=Environment.getExternalStorageDirectory()+"/boardVersion";
    public static String kalaite=Environment.getExternalStorageDirectory()+"/kalaite";

    public static void createAppPath(String sdPath){

        File appFilePath1=new File(appVer);
        if (!appFilePath1.exists()){
            appFilePath1.mkdir();
        }
        File appFilePath2=new File(boardVer);
        if (!appFilePath2.exists()){
            appFilePath2.mkdir();
        }
        File kalaiteFilePath=new File(kalaite);
        if (!kalaiteFilePath.exists()){
            kalaiteFilePath.mkdir();
        }

        if (sdPath==null){
            File appFilePath=new File(appPath);
            Log.e("tiwolf", "createAppPath内部路径: "+appPath+";path="+appFilePath.exists());
            if (!appFilePath.exists()){
                appFilePath.mkdir();
            }

//            File appFilePath1=new File(appVer);
//            if (!appFilePath1.exists()){
//                appFilePath1.mkdir();
//            }

            File downloadPath=new File(TestConfig.downloadFilePath);
            if (!downloadPath.exists()){
                downloadPath.mkdir();
            }
            File setPath=new File( FlyTextUtil.TXTDIR);
            if (!setPath.exists()){
                setPath.mkdir();
            }
        }else {
            File appFilePath=new File(sdPath+"/solar/");
            Log.e("tiwolf", "00外部sdcard的路径为: "+appFilePath );
            if (!appFilePath.exists()){
                appFilePath.mkdir();
                Log.e("tiwolf", "11外部sdcard的路径为: "+appFilePath );
            }

//            File appFilePath1=new File(sdPath+"/version");
//            if (!appFilePath1.exists()){
//                appFilePath1.mkdir();
//            }

            File downloadPath=new File(sdPath+"/solar/download/");
            if (!downloadPath.exists()){
                downloadPath.mkdir();
            }
            File setPath=new File(sdPath+ FlyTextUtil.TXTDIR);
            if (!setPath.exists()){
                setPath.mkdir();
            }
        }

    }

    /**
     * 外边会先将日期变成路径之后再输入,删除具体某一个
     * @param path 例如  “/2019.12.3/10:12”
     */
    public static void delFile(String path){
        File file=new File(path);
        if (file.exists() && file.isFile()){
            if (file.delete()){
                Log.e("tiwolf", "删除单个文件"+path+"成功");
            }else {
                Log.e("tiwolf", "删除单个文件"+path+"失败");
            }
        }else {
            Log.e("tiwolf", "删除单个文件失败："+path+"不存在！！！");
        }
    }

    /**
     * 删除某一个文件夹及里面的子文件,主要担心中病毒，里面额外生成其他文件
     * @param path 删除文件夹
     */
    public static boolean delFileAll(String path){
        //如果dir不以文件分隔符结尾，则自动添加文件分隔符
        if (!path.endsWith(File.separator)){
            path=path+File.separator;
        }
        File file=new File(path);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!file.exists()) || (!file.isDirectory())){
//            File[] files=file.listFiles();
//            for (int i = 0; i < files.length; i++) {
//                File f=files[i];
//                f.delete();
//            }
//            file.delete();
            Log.e("tiwolf", "删除目录失败："+path+"不存在！" );
            return false;
        }

        //删除子目录里面的文件
        File[] files=file.listFiles();
        for (File file1:files){
            //删除子文件
            if (file1.isFile()){
                delFile(file1.getAbsolutePath());
            }else if (file1.isDirectory()){
                //删除子目录
                delFileAll(file1.getAbsolutePath());
            }
        }

        if (file.delete()){
            Log.e("tiwolf", "删除目录"+path+"成功！" );
            return true;
        }else {
            Log.e("tiwolf", "删除目录"+path+"失败！" );
            return false;
        }
    }

    public static boolean delFileAll(String path,boolean flag){

        //如果dir不以文件分隔符结尾，则自动添加文件分隔符
        if (!path.endsWith(File.separator)){
            path=path+File.separator;
        }
        File file=new File(path);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!file.exists()) || (!file.isDirectory())){
//            File[] files=file.listFiles();
//            for (int i = 0; i < files.length; i++) {
//                File f=files[i];
//                f.delete();
//            }
//            file.delete();
            Log.e("tiwolf", "删除目录失败："+path+"不存在！" );
            return false;
        }

        //删除子目录里面的文件
        File[] files=file.listFiles();
        for (File file1:files){
            //删除子文件
            if (file1.isFile()){
//                delFile(file1.getAbsolutePath());
                File file2=new File(file1.getAbsolutePath());
                if (file2.exists() && file2.isFile()){
                    if (file2.delete()){
                        Log.e("tiwolf", "删除单个文件"+path+"成功");
                        flag=true;
                    }else {
                        Log.e("tiwolf", "删除单个文件"+path+"失败");
                    }
                }else {
                    Log.e("tiwolf", "删除单个文件失败："+path+"不存在！！！");
                }

            }else if (file1.isDirectory()){
                //删除子目录
                flag=delFileAll(file1.getAbsolutePath(),flag);
            }
        }

        file.delete();
        //如果标志为true,说明最起码可以删除一个文件，如此则表明这个文件没有删除过
        if (flag){
            return true;
        }else {
            return false;
        }

//        if (file.delete()){
//            Log.e("tiwolf", "删除目录"+path+"成功！" );
//            return true;
//        }else {
//            Log.e("tiwolf", "删除目录"+path+"失败！" );
//            return false;
//        }
    }

    /**
     * 获取文件download里面所有文件的名称
     * @return
     */
    public static List<String> getFileMd5(String sdPath){
        File file;
        if (sdPath==null || sdPath.length()==0){
            file=new File(appPath+"download/");
        }else {
            file=new File(sdPath+"/solar/download/");
        }

        if ((!file.exists()) || (!file.isDirectory())){
            Log.e("tiwolf", "删除目录失败：intefly不存在！" );
            return null;
        }

        File[] files=file.listFiles();
        ArrayList<String> strings=new ArrayList<>();
        for(File file1:files){
            if (file1.isFile()){
//                String name=file1.getName();
//                String[] names=name.split(".");
//                strings.add(names[0]);  //获取到MD5值‘
                strings.add(file1.getName());
            }else if (file1.isDirectory()){
                delFileAll(file1.getAbsolutePath());
            }
        }
        return strings;
    }

    /**
     * 删除download里面名称相对应的文件
     * @param name 例如  “/2019.12.3/10:12”
     */
    public static void delDownload(String sdPath,String name){
        File file;
        if (sdPath==null || sdPath.length()==0){
            file=new File(appPath+"download/"+name);
        }else {
            file=new File(sdPath+"/solar/download/"+name);
        }

        if (file.exists() && file.isFile()){
            if (file.delete()){
                Log.e("tiwolf", "删除单个文件"+name+"成功");
            }else {
                Log.e("tiwolf", "删除单个文件"+name+"失败");
            }
        }else {
            Log.e("tiwolf", "删除单个文件失败："+name+"不存在！！！");
        }
    }

    /**
     * 删除某一个文件夹里面的子文件,主要担心中病毒，里面额外生成其他文件
     * 删除solar文件夹 里面两天前的数据
     */
    public static void delSubFile(String sdPath,int dayNum){

        File file;
        if (sdPath==null || sdPath.length()==0){
            file=new File(appPath);
        }else {
            file=new File(sdPath+"/solar/");
        }

        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!file.exists()) || (!file.isDirectory())){
            Log.e("tiwolf", "删除目录失败：intefly不存在！" );
        }

        //删除子目录里面的文件
        File[] files=file.listFiles();
        for (File file1:files){
            //删除子文件
            if (file1.isFile()){
                Log.e("tiwolf", "delSubFile: "+file1.getName() );
                if (!"tiwolf.txt".equals(file1.getName())){
                    delFile(file1.getAbsolutePath());
                }
            }else if (file1.isDirectory()){
                //在这里判断是否是之前的文件夹 两天前的文件夹都删掉

                if (isNumeric(file1.getName())){
                    if (isDay(file1.getName(),dayNum)){
//                        Log.e("tiwolf", "delSubFile: 删除了"+file1.getName());
                        delFileAll(file1.getAbsolutePath());
                    }
                }else if (file1.getName().equals("music") || file1.getName().equals("video") || file1.getName().equals("download") || file1.getName().equals("set") || file1.getName().equals("log")) {

                } else {
                    //删除子目录
                    delFileAll(file1.getAbsolutePath());
                }

            }
        }
    }

    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }


    /**
     * 如果大于dayNum天数，则返回ture，删除。否则不删除
     * @param fileName
     * @param dayNum
     * @return
     */
    public static boolean isDay(String fileName,int dayNum){
        try {
            if (TimeUtil.getMillisLastDay(dayNum)/1000> TimeUtil.stringToLong(fileName,"yyyyMMdd")/1000){
//                Log.e("tiwolf", "isDay: "+dayNum );
//                Log.e("tiwolf", "isDay: "+TimeUtil.getMillisLastDay(dayNum) );
//                Log.e("tiwolf", "isDay: "+TimeUtil.stringToLong(fileName,"yyyyMMdd")/1000 );
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 创建版本存储的文件
     */
    public static File createVersionFile(String sdPath){

        File appFilePath;
//        if (sdPath==null || sdPath.length()==0){
//            appFilePath=new File(appVer);
//        }else {
//            appFilePath=new File(sdPath+"/version");
//        }
        appFilePath=new File(appVer);

        if (!appFilePath.exists()){
            appFilePath.mkdir();
        }

        File file=new File(appFilePath,"intefly.apk");
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 创建固件版本存储的文件
     */
    public static File createBoardVersionFile(String sdPath){

        File appFilePath;
//        if (sdPath==null || sdPath.length()==0){
//            appFilePath=new File(appVer);
//        }else {
//            appFilePath=new File(sdPath+"/version");
//        }
        appFilePath=new File(boardVer);

        if (!appFilePath.exists()){
            appFilePath.mkdir();
        }

        File file=new File(appFilePath,"update.zip");
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static void delSubFile(String path){

        File file=new File(path);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!file.exists()) || (!file.isDirectory())){
            Log.e("tiwolf", "删除目录失败：version不存在！" );
        }

        //删除子目录里面的文件
        File[] files=file.listFiles();
        for (File file1:files){
            //删除子文件
            if (file1.isFile()){
                android.util.Log.e("tiwolf", "delSubFile删除: "+file1.getName());
                file1.delete();
            }
        }
    }

    //获取外置sd卡路径
    public static String getStoragePath(Context mContext, boolean is_removale) {

        StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
        Class<?> storageVolumeClazz = null;
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            Object result = getVolumeList.invoke(mStorageManager);
            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String path = (String) getPath.invoke(storageVolumeElement);
                boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
                if (is_removale == removable) {
                    return path;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public void init_StoragePath(Context context) {
//        // flash dir
//
//        StorageManager mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
//        String flash_dir = Environment.getExternalStorageDirectory().getPath();
//        final List<VolumeInfo> volumes = mStorageManager.getVolumes();
//        Collections.sort(volumes, VolumeInfo.getDescriptionComparator());
//        for (VolumeInfo vol : volumes) {
//            if (vol.getType() == VolumeInfo.TYPE_PUBLIC) {
//                Log.d(TAG, "Volume path:" + vol.getPath());
//                DiskInfo disk = vol.getDisk();
//                if (disk != null) {
//                    if (disk.isSd()) {
//                        // sdcard dir
//                        StorageVolume sv = vol.buildStorageVolume(context,
//                                context.getUserId(), false);
//                        sdcard_dir = sv.getPath();
//                    } else if (disk.isUsb()) {
//                        // usb dir
//                    }
//                }
//            }
//        }
//
//        SDCARD_PATH = sdcard_dir;
//        Log.d(TAG, "sdcard_dir: " + sdcard_dir);
//    }


//    @RequiresApi(api = Build.VERSION_CODES.M)
//    public static String getSdCardPath(Context context) {
//
//        int TYPE_PUBLIC = 0;
//
//        File file = null;
//
//        String path = null;
//
//        StorageManager mStorageManager = context.getSystemService(StorageManager.class);
//
//
//        Class<?> mVolumeInfo = null;
//        try {
//            mVolumeInfo = Class.forName("android.os.storage.VolumeInfo");
//
//
//            Method getVolumes = mStorageManager.getClass().getMethod(
//                    "getVolumes");
//
//
//            Method volType = mVolumeInfo.getMethod("getType");
//
//            Method isMount = mVolumeInfo.getMethod("isMountedReadable");
//
//            Method getPath = mVolumeInfo.getMethod("getPath");
//
//            List<Object> mListVolumeinfo = (List<Object>) getVolumes
//                    .invoke(mStorageManager);
//
//
//
//            Log.d("getSdCardPath", "mListVolumeinfo.size="+mListVolumeinfo.size());
//
//            for (int i = 0; i < mListVolumeinfo.size(); i++) {
//
//                int mType = (Integer) volType.invoke(mListVolumeinfo.get(i));
//
//                Log.d("getSdCardPath", "mType=" + mType);
//
//                if (mType == TYPE_PUBLIC) {
//                    boolean misMount = (Boolean) isMount.invoke(mListVolumeinfo.get(i));
//                    Log.d("getSdCardPath", "misMount=" + misMount);
//                    if (misMount) {
//                        file = (File) getPath.invoke(mListVolumeinfo.get(i));
//                        if (file != null) {
//                            path = file.getAbsolutePath();
//                            Log.d("getSdCardPath", "path=" + path);
//                            return path;
//                        }
//                    }
//                }
//
//            }
//
//        } catch (ClassNotFoundException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (NoSuchMethodException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IllegalArgumentException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//        return "";
//    }
}
